<template>
  <dialog_item :dialogTitle="title" :visible.sync="fileUploadVisible" v-if="fileUploadVisible"  :isNotShowDefaultBtn="true" :appendBody="true" :dialogClass="nowOption=='iconUpload'?'dialogPaddingTop0':'fileUpload dialogPaddingTop0'">
    <el-container 
    v-if="nowOption=='import' || nowOption=='systemImport' || nowOption=='depImport'" v-loading="loading" :element-loading-text="$t('importing')"
    element-loading-background="rgba(0, 0, 0, 0.5)">
      
      <p v-if="nowOption=='import' || nowOption=='depImport'"><span>{{$t('annex')}}<a @click="installTemplate(nowOption)" style="color:#409EFF;cursor:pointer">{{$t('download_template')}}</a></span></p>
      <!-- 上传用户文件和部门文件 -->
      <el-upload
        class="upload-file"
        drag
        :action="getObpmUpload()"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :limit="limitNum"
        :on-remove="removeFile"
        :before-upload="beforeUploadFile"
        >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">{{$t('upload_txt')}}<em>{{$t('upload_click')}}</em></div>
      </el-upload>
      <el-header class="dialogBtn">
        <el-row :span="24">
          <!-- <el-col :span="9">文件上传</el-col> -->
          <el-col :span="24"  style="text-align:right">
            <span class="toolbar-buttons">
              <el-button type="primary" @click="onBack" size="small" plain>{{$t('cancel')}}</el-button>
              <el-button type="primary" @click="onSave" v-if="nowOption=='import' || nowOption=='depImport'" size="small">{{$t('confirm')}}</el-button>
              <el-button type="primary" @click="onSaveSystem" v-if="nowOption=='systemImport'" size="small">{{$t('confirm')}}</el-button>
            </span>
          </el-col>
        </el-row>
      </el-header>
    </el-container>
    
    <el-container v-if="nowOption=='iconUpload'" class="fileUploadContainer">
      <el-header> 
        <el-row :span="24">
          <el-col :span="9">{{$t('upload_img')}}</el-col>
        </el-row>
      </el-header>
      <!-- 企业域系统管理上传背景图片 -->
      <el-upload
        ref="upload"
        :class="nowOption=='iconUpload'?'uploadIcon':'upload-file'"
        drag
        :action="getUrl()"
        :on-success="uploadImageSuccess"
        :on-error="uploadError"
        :on-remove="removeImage"
        :data="data"
        :before-upload="beforeUploadIcon"
        >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">{{$t('upload_txt')}}<em>{{$t('upload_click')}}</em></div>
      </el-upload>
      <el-row class="marginTop30 marginBot10">
          <el-col :span="24"  style="text-align:right">
            <span class="toolbar-buttons">
              <el-button  @click="onIconBack" size="small">{{$t('cancel')}}</el-button>
              <el-button type="primary" @click="onSaveImage" size="small">{{$t('confirm')}}</el-button>
            </span>
          </el-col>
        </el-row>
    </el-container>
    <!-- </el-main> -->
    <weixin_result :visible.sync="importResultVisible" :weixinResult="importResult" :type="mode" @exit="onBack"/>

    </dialog_item>
</template>

<script>
import weixin_result from "@/components/weixin_result.vue";

export default {
  components:{
    weixin_result,
  },
  data() {
    return {
      icons:[],
      doUpload:'/authtime/uploads',
      fileData:[],
      data:{
        path:'/uploads/lib/icon/upload',
        filePath:'',
      },
      loading:false,
      limitNum:1,
      importResultVisible:false,
      importResult:{},
      mode:"file",
      title:'',
    };
  },
  
  created() {
    this.fileData=[];
    let year = new Date().getFullYear();
    this.data.filePath='/uploads/'+year;
    if(this.nowOption=='iconUpload'){
      if(this.selectOption)this.title=this.$t('upload_bgImg');
      else this.title=this.$t('upload_custom_icon');
    }else if(this.nowOption=='systemImport'){
      this.title= this.$t('import');
    }else if(this.nowOption == 'depImport'){
      this.title = 'Excel'+this.$t("department_import")
    }else{
      this.title= 'Excel'+this.$t('user_import');

    }
  },
  computed: {
    fileUploadVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      }
    }
  },
  props: ["visible","nowOption",'selectOption'],
  methods: {
    installTemplate(tabName){
      debugger
      let name = '';
      tabName == "depImport" ? name = this.$t('department') : name = this.$t('user')
      this.$api.installTemplate(name)
    },
    importData(){
      this.fileUploadVisible=true;
      
    },
    upSuccess(){
      
    },
    // 上传文件的校验
    beforeUploadFile(file) {
      if(this.title != this.$t('upload_bgImg')){
        let testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
        let extension = testmsg === 'xlsx' ||  testmsg === 'xls';
        let message = '上传文件只能是xlsx或者xls格式!';
        if(this.title == this.$t('import')){
          extension = testmsg === 'xml';
          message = '上传文件只能是xml格式!';
        }
        if(!extension) {
          this.$message({
            message: message,
            type: 'error'
          });
          return false;
        }
        return extension
      }
    },
    // 上传图片icon的校验
    beforeUploadIcon(file) {
      if(this.title == this.$t('upload_bgImg')){
        let testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
        const extension = testmsg === 'jpg' ||  testmsg === 'JPG' ||  testmsg === 'png' ||  testmsg === 'PNG' || testmsg === 'jpeg' || testmsg === 'JPEG' || testmsg === 'gif' ||  testmsg === 'GIF';
        if(!extension) {
          this.$message({
            message: '上传文件只能是jpg或者png格式!',
            type: 'error'
          });
          return false;
        }
        return extension
      }
    },
    newSubmitForm(){//确定上传
        this.$refs.newupload.submit();
    },
    uploadSuccess(res){
      this.fileData=res.data;
    },
    uploadImageSuccess(res){
      if(res.errcode==0){
        let preIconsUp=[...this.fileData]
        this.fileData=[...preIconsUp,...res.data];

      }else{
        this.$message({
          showClose: true,
          message: res.errmsg,
          type: "error"
        });
        this.$refs.upload.clearFiles();
      }

    },
    uploadError(err){
      this.$message.error(this.$t('msg_err_upload')+err)
    },
    removeImage(file){
      if(this.title != this.$t('upload_bgImg')){
        let delIcon=[];
        file.response.data.forEach(elm=>{
          delIcon.push(elm.filePath);
        })
        this.$emit("del", delIcon);
      }else{
         this.removeFile(file)
      }
    },
    removeFile(file){
      let index=-1,filepath="";
      file.response.data.forEach(elm=>{
        filepath=elm.filePath
      })
      index=this.fileData.findIndex(item=>{
           return item.filePath===filepath;
      })
      if(index!=-1){this.fileData.splice(index,1)}
    },
    onSave(){
      debugger
      let that= this;
      if(!this.fileData || !this.fileData[0]){
        this.$message({
          showClose: true,
          message: "请上传文件!",
          type: "error"
        });
        return false;
      }
      this.loading=true;
      if(this.nowOption == 'import'){
        this.$api.importUser({path:this.fileData[0].filePath}, {
          onSucess: resp => {
            if (resp && resp.data.errcode == 0) {
              that.importResult={
                "DEPT_ADD_FAIL":resp.data.data.general.DEPT_ADD_FAIL,
                "DEPT_ADD_SUCCESS":resp.data.data.general.DEPT_ADD_SUCCESS,
                "USER_ADD_FAIL":resp.data.data.general.USER_ADD_FAIL,
                "USER_ADD_SUCCESS":resp.data.data.general.USER_ADD_SUCCESS,
                "ERRORS":resp.data.data.detail
              }
              that.loading=false;
              that.onExit();
            } else {
              this.$message({
                message: resp.data.errmsg,
                type: "error"
              });
              this.loading=false;
            }
          }
        });
      }else{
        this.$api.departmentImport(this.fileData[0].filePath,
          {
            onSucess: resp => {
              if (resp && resp.data.data ) {
                this.$message({
                  message: resp.data.data,
                  type: "error"
                });
              } else {
                this.$message({
                  message: '导入成功',
                  type: 'success'
                });
                that.$emit("success")
                that.fileUploadVisible = false;
              }
              this.loading=false;
            }
          }
        )
      }

    },
    onSaveImage(){
      this.fileUploadVisible=false;
      this.$emit("checkUpload", this.fileData);
    },
    onSaveSystem(){
      let that=this;
      this.$api.importConfig({path:this.fileData[0].filePath}, {
        onSucess: resp => {
          if (resp && resp.data.errcode == 0) {
            this.$message({
              showClose: true,
              message: "导入成功!",
              type: "success"
            });
            that.loading=false;
            that.$emit("success")
            that.onBack();

          } else {
            this.$message({
              message: resp.data.errmsg,
              type: "error"
            });
            this.loading=false;

          }
        }
      });
    },
    onBack(){
      this.fileUploadVisible=false;
      this.$emit("success")
    },
    onIconBack(){
      let delIcon=[];
      this.fileData.forEach(elm=>{
        delIcon.push(elm.filePath);
      })
      if(delIcon.length>0)
      this.$emit("del", delIcon);      
      this.fileUploadVisible=false;

    },
    onExit(){
      this.importResultVisible=true;
    },
    // 上传icon路径
    getUrl(){
      return this.$api.getFileUrl(this.doUpload+"?path="+this.data.path+"&icon=true")
    },
    // 上传文件路径
    getFileUrl(){
      return this.$api.getFileUrl(this.doUpload+"?path="+this.data.filePath+"&icon=false")
    },
    getObpmUpload() {
      let applicationId = ''
      let href = window.location.href
      if(href.indexOf('applicationId') >= 0) {
        let urlArrayF = href.split("?");
        let urlArray;
        if(urlArrayF[1]) {
          urlArray = urlArrayF[1].split("&")
          if(urlArray && urlArray.length > 0) {
            for(let i = 0;i < urlArray.length; i ++) {
              let val = urlArray[i].split("=");
              if(val[0] == 'applicationId') {
                applicationId = val[1] 
                break;
              }
            }
          }
        }
      }
      return `/obpm/api/runtime/upload?applicationId=${applicationId}&allowedTypes=&fieldId=&fileSaveMode=&path=&actionType=`
    }
    
  }
};
</script>

<style lang="scss" scoped>
</style>